<?php

namespace App\Http\Controllers\Admin\Content;

use App\Http\Controllers\Controller;
use App\Repositories\Article\ArticleCategoryRepository;
use Illuminate\Http\Request;

class CategoryController extends Controller
{

    protected array $validateMessages = [
        'parent_id.*' => '请选择父级分类',
        'name.*' => '请输入正确的名称',
        'slug.*' => '请输入正确的 slug',
        'description.*' => '请输入正确的描述',
        'sort.*' => '请输入正确的排序',
        'status.*' => '请输入正确的状态',
    ];

    public function __construct(Request $request, ArticleCategoryRepository $repository)
    {
        $this->request = $request;
        $this->repository = $repository;
    }


    public function index()
    {
        return $this->inertia('admin/content/category/index', [
            'data' => $this->repository->tree(),
            'title' => '文章分类',
            'options' => $this->repository->getSelect(),
        ]);
    }

    public function show(int $id)
    {
        $row = $this->repository->getById($id);
        return [
            'data' => [
                'id' => $row->id,
                'parent_id' => $row->parent_id== 0 ? null : $row->parent_id,
                'name' => $row->name,
                'slug' => $row->slug,
                'description' => $row->description,
                'sort' => $row->sort,
                'status' => $row->status,
                'created_at' => $row->created_at->format('Y-m-d'),
            ],
        ];
    }

    public function store()
    {
        $params = $this->validate(
            $this->request,
            [
                'parent_id' => 'nullable|integer',
                'name' => 'required|string',
                'slug' => 'required|string|unique:article_categories,slug',
                'description' => 'nullable|string',
                'sort' => 'required|integer',
                'status' => 'required|integer',
            ],
            $this->validateMessages
        );
        $params['parent_id'] = $params['parent_id'] ?? 0;
        $this->repository->create($params);
        return $this->responseCreated();
    }

    public function update($id)
    {
        $params = $this->validate(
            $this->request,
            [
                'parent_id' => 'nullable|integer',
                'name' => 'required|string',
                'slug' => 'required|string|unique:article_categories,slug,' . $id,
                'description' => 'nullable|string',
                'sort' => 'required|integer',
                'status' => 'required|integer',
            ],
            $this->validateMessages
        );
        $row = $this->repository->getById($id);
        $row->update($params);
        return $this->responseSuccess();
    }

    public function destroy($id)
    {
        $row = $this->repository->getById($id);
        if ($row->articles()->count() > 0) {
            abort(403,'该分类下有文章,暂不能删除!');
        }
        $row->delete();
        return $this->responseDeleted();
    }
}
